package thread;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;

/**
 * ArrayList,LinkedList和HashSet都不是并发安全集合
 *
 * 使用Collections.synchronizedList把一个现有的集合转换为并发安全的集合
 */
public class SyncDemo5 {
    public static void main(String[] args) {
//        Collection <Integer> c=new ArrayList<>();//其他俩也一样运行都不是带同步锁的
//        Collection <Integer> c=new LinkedList<>();
//        Collection <Integer> c=new HashSet<>();

//        Collection<Integer> c = Collections.synchronizedList(new ArrayList<>());
        Collection<Integer> c = Collections.synchronizedSet(new HashSet<>());
        Thread t1 = new Thread(){
            public void run(){
                for (int i = 0; i < 1000; i++) {
                    c.add(i);
                }
            }
        };
        Thread t2 = new Thread(){
            public void run(){
                for (int i = 0; i < 1000; i++) {
                    c.add(i);
                }
            }
        };
        t1.start();
        t2.start();

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(c);
        System.out.println(c.size());
    }
}
